package app;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.lang.Character.Subset;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import info.clearthought.layout.TableLayout;

import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextField;

import javax.swing.WindowConstants;



/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class Captcha extends javax.swing.JFrame  {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JLabel captcha;
	private JTextField jCaptcha;
	private JButton renew;
	private JButton bCancelar;
	private JButton bAceptar;
	private Main m;
	private int modo;
	private String challenge = "";
	

	{
		//Set Look & Feel
		try {
			javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
		} catch(Exception e) {
			e.printStackTrace();
		}
	}


	/**
	* Auto-generated main method to display this JFrame
	*/
		
	public Captcha(Main main) {
		super();
		initGUI();
		m=main;
		
	}
	
	public void setModo(int mo) {
		modo=mo;
	}
	private BufferedImage scaleImage(BufferedImage image, int imageType,
			int newWidth, int newHeight) {
		// http://www.technojeeves.com/joomla/index.php/free/67-scale-an-image-in-java

		double thumbRatio = (double) newWidth / (double) newHeight;
		int imageWidth = image.getWidth(null);
		int imageHeight = image.getHeight(null);
		double aspectRatio = (double) imageWidth / (double) imageHeight;

		if (thumbRatio < aspectRatio) {
			newHeight = (int) (newWidth / aspectRatio);
		} else {
			newWidth = (int) (newHeight * aspectRatio);
		}

		// Draw the scaled image
		BufferedImage newImage = new BufferedImage(newWidth, newHeight,
				imageType);
		Graphics2D graphics2D = newImage.createGraphics();
		graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
				RenderingHints.VALUE_INTERPOLATION_BILINEAR);
		graphics2D.drawImage(image, 0, 0, newWidth, newHeight, null);

		return newImage;
	}
	
	
	public void mostrarImagen(String url) throws Exception {
		
		URL imageurl;
		Image newimg = null;
		ImageIcon icon = null;
		BufferedImage imagen = null;
		imageurl = new URL(url);
		System.out.println("Obteniendo imagen...");
		System.out.println(url);
		imagen = ImageIO.read(imageurl);
		System.out.println("Listo");
		int alto = imagen.getHeight();
		int ancho = imagen.getWidth();

		if (ancho > 450 || alto > 179)
			newimg = scaleImage(imagen, BufferedImage.TYPE_INT_ARGB, 450, 179);

		else
			newimg = imagen;
		icon = new ImageIcon(newimg);

		captcha.setIcon(icon);
		

	}
	
	public void resetGui() {
		jCaptcha.setText("");
	}
	
	private void initGUI() {
		try {
			TableLayout thisLayout = new TableLayout(new double[][] {{7.0, TableLayout.FILL, TableLayout.FILL, 78.0, TableLayout.FILL, TableLayout.FILL, 7.0}, {7.0, TableLayout.FILL, TableLayout.FILL, TableLayout.FILL, TableLayout.FILL, 7.0}});
			thisLayout.setHGap(5);
			thisLayout.setVGap(5);
			getContentPane().setLayout(thisLayout);
			setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
			this.setTitle("Ingresar captcha");
			{
				captcha = new JLabel();
				getContentPane().add(captcha, "1,1,5,2,c,f");
			}
			{
				jCaptcha = new JTextField();
				getContentPane().add(jCaptcha, "2, 3, 4, 3, f, c");
				jCaptcha.setFont(new java.awt.Font("Arial",0,12));
			}
			{
				bAceptar = new JButton();
				getContentPane().add(bAceptar, "2,4,f,c");
				bAceptar.setText("Aceptar");
				bAceptar.setFont(new java.awt.Font("Arial",0,12));
				bAceptar.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent evt) {
						bAceptarActionPerformed(evt);
					}
				});
			}
			{
				bCancelar = new JButton();
				getContentPane().add(bCancelar, "4,4,f,c");
				bCancelar.setText("Cancelar");
				bCancelar.setFont(new java.awt.Font("Arial",0,12));
				bCancelar.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent evt) {
						bCancelarActionPerformed(evt);
					}
				});
			}
			{
				renew = new JButton();
				getContentPane().add(renew, "5,3,l,c");
				//renew.setText("Otra");
				renew.setFont(new java.awt.Font("Ubuntu",0,12));
				renew.setIcon(new ImageIcon(getClass().getClassLoader().getResource("app/reload.png")));
				renew.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
				renew.setOpaque(false);
				renew.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent evt) {
						try {
							renewActionPerformed(evt);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				});
			}
			pack();
			this.setSize(467, 302);
			this.setIconImage(new ImageIcon(getClass().getClassLoader().getResource("app/postinga16x16.png")).getImage());
		} catch (Exception e) {
		    //add your error handling code here
			e.printStackTrace();
		}
	}
	
	private void bAceptarActionPerformed(ActionEvent evt) {
		try {
			String [] arr =	jCaptcha.getText().split(" ");
			m.habiliarPost();
			
			if (modo==0){
				System.out.println("Vuelvo a T!");
				m.postearEnT(m.getUsuario(),m.getContrasenia(), true,arr[0],arr[1]);
			}
			if (modo==2){
				System.out.println("Vuelvo a P!");
				m.postearEnP(m.getUsuario(),m.getContrasenia(), true,arr[0],arr[1]);
			}
			
		} catch (Exception e) {
			
		}
		this.dispose();
	}
	
	private void bCancelarActionPerformed(ActionEvent evt) {
		m.habiliarPost();
		this.dispose();
	}
	
	private void renewActionPerformed(ActionEvent evt) throws Exception {
		//GET /recaptcha/api/reload?c=03AHJ_Vutjw7BhLmXcHNW-9H4wlKr9IlaHy5tcakfhx83bNpV6zr2geisajGbze7_-WKWqEeOShTU_foCcNSjN2IWBxj3FhkUkocMgXIWOovyBxgxRUjoJfLGoiEDrv4o56ssV1-_McwrUVHKiK5GABygA41euKTPJ6Q&k=6Le8jQQAAAAAAGt1bzJsaHKCoLMWt6NFHupdtxf9&reason=r&type=image&lang=es
		 URLConnection conn;
		 String line2 = "";
		 URL siteUrl = null;
		 if (modo==0)   siteUrl = new URL("http://www.google.com/recaptcha/api/reload?c=03AHJ_Vutjw7BhLmXcHNW-9H4wlKr9IlaHy5tcakfhx83bNpV6zr2geisajGbze7_-WKWqEeOShTU_foCcNSjN2IWBxj3FhkUkocMgXIWOovyBxgxRUjoJfLGoiEDrv4o56ssV1-_McwrUVHKiK5GABygA41euKTPJ6Q&k=6Le8jQQAAAAAAGt1bzJsaHKCoLMWt6NFHupdtxf9&reason=r&type=image&lang=es");
		 if (modo==2)   siteUrl = new URL("http://www.google.com/recaptcha/api/reload?c=03AHJ_VusQgIgVR408QiDXu_Yjtyr657BnJ8-aOd380fnKR23NqXdrLn_B5CJ7S4onJ_dJjLk0zWA1xlkvGnJlVC-gaA_H7-I9lqs5YgKLJu7fr7i2CMcePvnT7fJJ7QqHNtl7dooZLxaQMxNIcEuM2Pn7L2u68x52xw&k=6Le9jQQAAAAAADUXWDQ3Bj9mqDYQSWHHTghMuUVf&reason=r&type=image&lang=es");

		   conn = (HttpURLConnection) siteUrl.openConnection();
		((HttpURLConnection) conn).setRequestMethod("GET");
		
		BufferedReader in2 = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		
		String salida="";
		while((line2=in2.readLine())!=null)	 
			salida=salida+line2;
		
		challenge=salida.substring(25,salida.length()-12);
		System.out.println("NUEVA CHALLENGE: "+challenge);
		m.setChallenge(challenge);
		mostrarImagen("http://www.google.com/recaptcha/api/image?c="+challenge);
		jCaptcha.requestFocus();
		
		
	}

}
